package org.ph.share.lock.test.thread2;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 探究lock的可打断特性
 *
 * @author Hush.
 * @since 2023/1/18 19:47
 */
@Slf4j
public class Thread20 {
    static ReentrantLock lock = new ReentrantLock();

    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(() -> {
            try {
                // log.error("竞争锁");
                // lock.lock(); //配合主线程就会死锁
                log.error("尝试获取锁");
                // 若没有锁竞争,就会获取到锁
                // 有竞争,则会进入阻塞队列,可以被其他线程interrupt()中断，从而退出竞争
                lock.lockInterruptibly();
            } catch (InterruptedException e) {
                log.error("中断");
                throw new RuntimeException(e);
            }
            try {
                log.info("执行方法");
            } finally {
                lock.unlock();
            }

        }, "t1");

        // 在t1启动前，主线程率先得到锁,t1进入阻塞状态
        lock.lock();
        t1.start();
        TimeUnit.SECONDS.sleep(1);
        // 中断t1
        log.info("中断t1");
        t1.interrupt();
    }
}
